package com.nachuan.pdd.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.nachuan.pdd.entity.request.ApiRequestParam;
import com.nachuan.pdd.internal.AjaxResult;
import com.nachuan.pdd.internal.PddClient;
import com.pdd.pop.sdk.http.PopBaseHttpRequest;
import com.pdd.pop.sdk.http.PopBaseHttpResponse;
import com.pdd.pop.sdk.http.PopClient;
import com.pdd.pop.sdk.http.api.pop.request.PddMallInfoGetRequest;
import com.pdd.pop.sdk.http.api.pop.request.PddPmcUserPermitRequest;
import com.pdd.pop.sdk.http.api.pop.request.PddPopAuthTokenCreateRequest;
import com.pdd.pop.sdk.http.api.pop.request.PddPopAuthTokenRefreshRequest;
import com.pdd.pop.sdk.http.api.pop.request.PddServicemarketContractSearchRequest;
import com.pdd.pop.sdk.http.api.pop.response.PddMallInfoGetResponse;
import com.pdd.pop.sdk.http.api.pop.response.PddPmcUserPermitResponse;
import com.pdd.pop.sdk.http.api.pop.response.PddPopAuthTokenCreateResponse;
import com.pdd.pop.sdk.http.api.pop.response.PddPopAuthTokenRefreshResponse;
import com.pdd.pop.sdk.http.api.pop.response.PddServicemarketContractSearchResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 拼多多 认证授权接口
 *
 * @author : 古书柳
 * @date : 06 : 02 : 2025/2/6
 */
@Slf4j
@RestController
public class PddApi {

	@GetMapping("/api/redirect_uri")
	public String auth(String code, String state, HttpServletRequest request, HttpServletResponse response) {
		log.info("---------------------  授权回调数据 -> code: {}, state: {}", code, state);
		if (StrUtil.isBlank(code)) {
			throw new RuntimeException("授权失败 、code无效");
		}
		PopClient popClient = PddClient.getSingleton();
		try {
			PddPopAuthTokenCreateResponse authTokenCreateResponse = null;
			// 获取token数据
			{
				PddPopAuthTokenCreateRequest pddPopAuthTokenCreateRequest = new PddPopAuthTokenCreateRequest();
				pddPopAuthTokenCreateRequest.setCode(code);
				authTokenCreateResponse = popClient.syncInvoke(pddPopAuthTokenCreateRequest);
				if (authTokenCreateResponse.getErrorResponse() != null) {
					throw new RuntimeException(authTokenCreateResponse.getErrorResponse().getSubMsg());
				}
				log.info("pdd Token信息 -> {}", JSONUtil.toJsonStr(authTokenCreateResponse.getPopAuthTokenCreateResponse()));
			}
			// 获取店铺信息数据
			PddMallInfoGetResponse pddMallInfoGetResponse = null;
			{
				PddMallInfoGetRequest pddMallInfoGetRequest = new PddMallInfoGetRequest();
				pddMallInfoGetResponse = popClient.syncInvoke(pddMallInfoGetRequest, authTokenCreateResponse.getPopAuthTokenCreateResponse().getAccessToken());
				if (pddMallInfoGetResponse.getErrorResponse() != null) {
					throw new RuntimeException(pddMallInfoGetResponse.getErrorResponse().getErrorMsg());
				}
				log.info("pdd 店铺信息    -> {}", JSONUtil.toJsonStr(pddMallInfoGetResponse.getMallInfoGetResponse()));
			}
			// 获取店铺授权信息
			PddServicemarketContractSearchResponse pddServicemarketContractSearchResponse = null;
			{
				PddServicemarketContractSearchRequest pddServicemarketContractSearchRequest = new PddServicemarketContractSearchRequest();
				pddServicemarketContractSearchRequest.setMallId(Long.valueOf(authTokenCreateResponse.getPopAuthTokenCreateResponse().getOwnerId()));
				pddServicemarketContractSearchResponse = popClient.syncInvoke(pddServicemarketContractSearchRequest);
				if (pddServicemarketContractSearchResponse.getErrorResponse() != null) {
					throw new RuntimeException(pddServicemarketContractSearchResponse.getErrorResponse().getErrorMsg());
				}
				log.info("pdd 授权信息    -> {}", JSONUtil.toJsonStr(pddServicemarketContractSearchResponse.getServicemarketContractSearchResponse()));
			}
			// 开启消息推送权限
			PddPmcUserPermitResponse pddPmcUserPermitResponse = null;
			{
				pddPmcUserPermitResponse = popClient.syncInvoke(new PddPmcUserPermitRequest(), authTokenCreateResponse.getPopAuthTokenCreateResponse().getAccessToken());
				if (pddPmcUserPermitResponse.getErrorResponse() != null) {
					throw new RuntimeException(pddPmcUserPermitResponse.getErrorResponse().getErrorMsg());
				}
				log.info("pdd 开启消息推送权限 -> {}", JSONUtil.toJsonStr(pddPmcUserPermitResponse.getPmcUserPermitResponse()));
			}
			// 发送授权信息
			{
				Map<String, Object> param = new HashMap<>();
				{
					param.put("tokenInfo", authTokenCreateResponse.getPopAuthTokenCreateResponse());
					param.put("state", state);
					param.put("mallInfo", pddMallInfoGetResponse.getMallInfoGetResponse());
					param.put("authServiceInfo", pddServicemarketContractSearchResponse.getServicemarketContractSearchResponse());
				}
				log.info("发送授权信息 -> {}", JSONUtil.toJsonStr(param));
				HttpUtil.post("https://aliapi.gonghuo.shop/api/pdd/auth/callback", JSONUtil.toJsonStr(param));
			}

		} catch (Exception e) {
			log.error("授权失败 -> {}", e.getMessage());
			return "授权失败  " + e.getMessage();
		} finally {
			log.info("---------------------  授权回调结束");
		}

		return "授权成功! 请关闭此页面即可!";
	}

	/**
	 * 服务市场订单履约查询
	 */
	@PostMapping("/pdd.servicemarket.contract.search")
	public AjaxResult dian_pu_shou_quan(String token, String mallId) {
		PopClient singleton = PddClient.getSingleton();
		PddServicemarketContractSearchResponse pddServicemarketContractSearchResponse = null;
		{
			try {
				PddServicemarketContractSearchRequest pddServicemarketContractSearchRequest = new PddServicemarketContractSearchRequest();
				pddServicemarketContractSearchRequest.setMallId(Long.valueOf(mallId));
				pddServicemarketContractSearchResponse = singleton.syncInvoke(pddServicemarketContractSearchRequest);
				if (pddServicemarketContractSearchResponse.getErrorResponse() != null) {
					throw new RuntimeException(pddServicemarketContractSearchResponse.getErrorResponse().getErrorMsg());
				}
				log.info("服务市场订单履约查询   -> {}", JSONUtil.toJsonStr(pddServicemarketContractSearchResponse.getServicemarketContractSearchResponse()));

			} catch (Exception e) {
				return AjaxResult.error("发生错误 :" + e.getMessage());
			}
		}
		return AjaxResult.success(pddServicemarketContractSearchResponse.getServicemarketContractSearchResponse());
	}

	/**
	 * 获取店铺信息
	 */
	@PostMapping("/pdd.mall.info.get")
	public AjaxResult dian_pu_shu_ju(String token, String mallId) {
		PopClient singleton = PddClient.getSingleton();
		PddMallInfoGetResponse pddMallInfoGetResponse = null;
		{
			try {
				PddMallInfoGetRequest pddMallInfoGetRequest = new PddMallInfoGetRequest();
				pddMallInfoGetResponse = singleton.syncInvoke(pddMallInfoGetRequest, token);
				if (pddMallInfoGetResponse.getErrorResponse() != null) {
					throw new RuntimeException(pddMallInfoGetResponse.getErrorResponse().getErrorMsg());
				}
				log.info("获取店铺信息    -> {}", JSONUtil.toJsonStr(pddMallInfoGetResponse.getMallInfoGetResponse()));
			} catch (Exception e) {
				return AjaxResult.error("发生错误 :" + e.getMessage());
			}
		}
		return AjaxResult.success(pddMallInfoGetResponse.getMallInfoGetResponse());
	}

	/**
	 * 刷新Access Token
	 */
	@PostMapping("/pdd.pop.auth.token.refresh")
	public AjaxResult refreshToken(String refreshToken) {
		PddPopAuthTokenRefreshResponse response = null;
		PopClient singleton = PddClient.getSingleton();
		PddPopAuthTokenRefreshRequest request = new PddPopAuthTokenRefreshRequest();
		request.setRefreshToken(refreshToken.toString());
		try {
			response = singleton.syncInvoke(request);
			if (response.getErrorResponse() != null) {
				throw new RuntimeException(response.getErrorResponse().getSubMsg());
			}
		} catch (Exception e) {
			throw new RuntimeException("获取店铺认证信息失败" + e.getMessage());
		}
		return AjaxResult.success(response.getPopAuthTokenRefreshResponse());
	}

	/**
	 * 公共请求处理
	 *
	 * @param apiRequestParam
	 * @param <T>
	 * @return
	 */
	@PostMapping("/commonApi")
	public <T extends PopBaseHttpResponse> AjaxResult commonApi(@RequestBody ApiRequestParam apiRequestParam) {
		if (StrUtil.isBlank(apiRequestParam.getToken())) throw new RuntimeException("token 参数不能为空");
		if (StrUtil.isBlank(apiRequestParam.getRequestClassPackageName())) {
			throw new RuntimeException("requestClassPackageName 参数不能为空");
		}
		// 加载请求类
		Class<?> requestClass = null;
		try {
			requestClass = Class.forName(apiRequestParam.getRequestClassPackageName());
		} catch (Exception e) {
			throw new RuntimeException("requestClassPackageName 参数有误请检查！");
		}
		{
			if (!PopBaseHttpRequest.class.isAssignableFrom(requestClass)) {
				throw new IllegalArgumentException("请求类必须是PopBaseHttpRequest的子类");
			}
		}
		// 创建请求类
		PopBaseHttpRequest<T> requestInstance = null;
		try {
			requestInstance = (PopBaseHttpRequest<T>) requestClass.getDeclaredConstructor().newInstance();
		} catch (Exception e) {
			throw new RuntimeException("请求类实例化失败 : " + e.getMessage());
		}
		// 使用Hutool的BeanUtil将params映射到请求实例中
		if (apiRequestParam.getApiParam() != null) {
			BeanUtil.fillBeanWithMap(apiRequestParam.getApiParam(), requestInstance, true);
		}
		PopClient singleton = PddClient.getSingleton();
		T response = null;
		try {
			response = singleton.syncInvoke(requestInstance, apiRequestParam.getToken());
		} catch (Exception e) {
			throw new RuntimeException("请求时发生错误 :" + e.getMessage());
		}
		// 检查响应中是否有错误信息
		if (response != null && response.getErrorResponse() != null) {
			throw new RuntimeException("拼多多响应错误 :" + response.getErrorResponse().getErrorMsg());
		}
		return AjaxResult.success(response);
	}
}
